
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"

#include "tmGpio.h"

static uint8_t gStationNum;

/**
 * @brief Init For LED IO
 */
void TmGpioLedInit()
{
    //zero-initialize the config structure.
    gpio_config_t io_conf = {};
    //disable interrupt
    io_conf.intr_type = GPIO_INTR_DISABLE;
    //set as output mode
    io_conf.mode = GPIO_MODE_OUTPUT;
    //bit mask of the pins that you want to set,e.g.GPIO18/19
    io_conf.pin_bit_mask = (1ULL<<12) | (1ULL<<13);
    //disable pull-down mode
    io_conf.pull_down_en = 0;
    //disable pull-up mode
    io_conf.pull_up_en = 0;
    //configure GPIO with the given settings
    gpio_config(&io_conf);

    gpio_set_level(12, 0);
    gpio_set_level(13, 0);

    //interrupt of rising edge
    // io_conf.intr_type = GPIO_INTR_POSEDGE;
    //bit mask of the pins, use GPIO4/5 here
    io_conf.pin_bit_mask = (1ULL<<6) | (1ULL<<7);
    //set as input mode
    io_conf.mode = GPIO_MODE_INPUT;
    //enable pull-up mode
    io_conf.pull_up_en = 1;
    io_conf.pull_down_en = 0;
    gpio_config(&io_conf);

    gStationNum = gpio_get_level(6)==0?0x0:0x1;
    gStationNum |= gpio_get_level(7)==0?0x0:0x2;
}

uint8_t TmGpioGetStationNum()
{
    return gStationNum;
}

void TmGpioSetLedLv1(uint8_t i)
{
    gpio_set_level(12, i==0?0:1);
}
void TmGpioSetLedLv2(uint8_t i)
{
    gpio_set_level(13, i==0?0:1);
}


void TmGpioTolLedLv1()
{
    static bool sTolFlag = false;
    gpio_set_level(12, sTolFlag);
    sTolFlag = !sTolFlag;
}
void TmGpioTolLedLv2()
{
    static bool sTolFlag = false;
    gpio_set_level(13, sTolFlag);
    sTolFlag = !sTolFlag;
}

/**
 * @brief Init For Step Motor IO
 * include STEP GPIO and DIR GPIO
 */
void TmGpioMotorInit()
{
    //zero-initialize the config structure.
    gpio_config_t io_conf = {};
    //disable interrupt
    io_conf.intr_type = GPIO_INTR_DISABLE;
    //set as output mode
    io_conf.mode = GPIO_MODE_OUTPUT;
    //bit mask of the pins that you want to set,e.g.GPIO18/19
    io_conf.pin_bit_mask = (1ULL<<TM_AXIS_X_DIR) 
        | (1ULL<<TM_AXIS_Y_DIR) | (1ULL<<TM_AXIS_Z_DIR) | (1ULL<<TM_MOTOR_EN);
    //disable pull-down mode
    io_conf.pull_down_en = 0;
    //disable pull-up mode
    io_conf.pull_up_en = 0;
    //configure GPIO with the given settings
    gpio_config(&io_conf);

    TmMotorDirResX;
    TmMotorDirResY;
    TmMotorDirResZ;
    TmMotorEnRes;
}

// void TmGpioMotorSetDir(gpio_num_t io, uint32_t level)